/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package services;

import com.google.gson.Gson;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Booking;
import model.Flight;
import model.Receipt;

/**
 *
 * @author Jorge
 */
public class ConcreteDatabaseService extends ContreteService implements DatabaseService{

    public ConcreteDatabaseService() {
        super("http://localhost:8084/WebServiceFlightBooking/webresources/database");
    }
    
    

    @Override
    public Flight[] searchFlights(String from, String to, String departureDate, String arrivalDate) {
        try {
            URL recurso = new URL(urlBase + "?from="+from+"&to="+to+"&departureDate="
                    +departureDate+"&arrivalDate="+arrivalDate);
            HttpURLConnection conexao = (HttpURLConnection) recurso.openConnection();
            conexao.setRequestMethod("GET");
            conexao.setDoOutput(true);
            
            System.out.println(urlBase + "?from="+from+"&to="+to+"&departureDate="
                    +departureDate+"&arrivalDate="+arrivalDate);
            
            conexao.connect();

            
            String res = lerInputStream(conexao.getInputStream());
            conexao.disconnect();
            
            Flight[] dump = new Gson().fromJson(res, Flight[].class);
            
            return dump;
        } catch (IOException ex) {
            Logger.getLogger(ConcreteDatabaseService.class.getName()).log(Level.SEVERE, null, ex);
            
        }
        return null;

    }

    @Override
    public boolean updateInformation(Booking booking, Receipt receipt) {
        try {
            String b = new Gson().toJson(booking).toString();
            String r = new Gson().toJson(receipt).toString();
            
           URL recurso = new URL(urlBase);
            HttpURLConnection conexao = (HttpURLConnection) recurso.openConnection();
            conexao.setRequestMethod("PUT");
            conexao.setRequestProperty("content-type", "application/json");
            conexao.setDoOutput(true);
            
            conexao.connect();
            
            String res = lerInputStream(conexao.getInputStream());
            conexao.disconnect();
            
            Boolean bo = new Gson().fromJson(res, Boolean.class);
            
            return bo;
        } catch (IOException ex) {
            Logger.getLogger(ConcreteDatabaseService.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }
    
}
